package wechatpublic

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"log"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"

	"yundian/internel/pkg/authorized"
)

const (
	sendTemplateURL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s"
)

func WeChatSendTemplate(bodyData map[string]interface{}) (result ResSendTemplate, err error) {
	var accessToken string
	//获取授权token
	t := global.Rdb.TTL(context.Background(), utils.Join("cgi-bin-Access-Token")).Val()
	if t <= 0 {
		respAccessToken, _ := authorized.GetAccessToken()
		accessToken = respAccessToken.AccessToken
	} else {
		s := global.Rdb.Get(context.Background(), utils.Join("cgi-bin-Access-Token")).Val()
		accessToken = s
	}

	urlStr := fmt.Sprintf(sendTemplateURL, accessToken)

	payload, _ := json.Marshal(bodyData)

	headers := map[string]string{"Content-Type": "application/json"}

	resp, err := authorized.PostRequest(urlStr, headers, bytes.NewReader(payload))
	body, _ := json.Marshal(resp)
	_ = json.Unmarshal(body, &result)
	if err != nil || result.Errcode != 0 {
		log.Println("模板消息推送失败", result.Errmsg)
		return result, err
	}

	return result, nil
}

func WeChatSendTemplateTest() {

	data := map[string]interface{}{}
	templateMsg := &TemplateMsg{}
	tempData := &TemplateData{}

	//设置模板推送信息
	templateMsg.ToUser = "oJeZ-6tSJvBpvYv_2ZPJGBjCS8iU"
	templateMsg.TemplateID = "hvcXArpPbwRKT-bibZ6XwLkC1PP9XG69a7b8cyu-GZk"
	templateMsg.Data = tempData

	tempData.First.Value = "存在新服务提示"
	tempData.Keyword1.Value = "测试先生"
	tempData.Keyword2.Value = "17745465656"
	tempData.Remark.Value = "请尽快处理"

	msgByte, _ := json.Marshal(templateMsg)
	json.Unmarshal(msgByte, &data)

	resp, err := WeChatSendTemplate(data)
	fmt.Println(resp, err)

}
